<?php
/**
 * Created by PhpStorm.
 * User: kwibon
 * Date: 2018/11/26
 * Time: 11:18
 */
namespace app\api\controller;

use app\admin\controller\Product;
use app\common\controller\Api;
use app\api\controller\KbxToken as KbxToken;
use think\Cookie;
use think\Exception;
use think\log;
use think\Db;
use app\wap\controller\Kbxcoupon;
use app\api\model\Standard as SDModel;
use app\common\controller\Token as UserToken;
use think\Request;

class KbxOrder extends Api
{
    //使用trait方法复用
    use UserToken;

    public function _initialize()
    {
        header('Access-Control-Allow-Origin:*');

        Log::init([
            'type'  =>  'File',
            'path'  =>  APP_PATH.'logs/'
        ]);
    }

    public  $statusArr = array(
        '1' => array(
            'orderStatus' => 'pending',
            'paymentStatus' => 'pending',
        ),
        '2' => array(
            'orderStatus' => 'pending',
            'paymentStatus' => 'paid',
        ),
        '3' => array(
            'orderStatus' => 'finished',
            'paymentStatus' => 'paid',
        ),
        '4' => array(
            'orderStatus' => 'reviewed',
            'paymentStatus' => 'paid',
        ),
        '5' => array(
            'orderStatus' => 'toBeStarting',
            'paymentStatus' => 'refunding',
        ),
        '6' => array(
            'orderStatus' => 'canceled',
            'paymentStatus' => 'refunding',
        ),
        '7' => array(
            'orderStatus' => 'expired',
            'paymentStatus' => 'pending',
        ),
        '8' => array(
            'orderStatus' => 'canceled',
            'paymentStatus' => 'refunded',
        ),
        '9' => array(
            'orderStatus' => 'toBeStarting',
            'paymentStatus' => 'rejected',
        ),
        '10' => array(
            'orderStatus' => 'unknown',
            'paymentStatus' => 'pending',
        )
    );
    //前置方法 验证token only后是需要执行前置的方法 'only'=>’xxx,yyy,zzz‘
    protected $beforeActionList = [
        'checkSign'=>[
            'only'=>'kbx_custom_order_latest,getorderdetailbyorderid'
        ],
        'checkUserToken'=>[
            'only'=>'kbx_custom_order_latest'
        ],
        'returnUserToken'=>[
            'only'=>'getorderdetailbyorderid'
        ]
    ];
    //调用订单系统  create Or Update订单接口
    public function kbx_operate_order($orderType,$data,$isRefundCarPool=false)
    {
        $kbxToken = new KbxToken();
        $TypeArr = array(
            'Ticket_FIT'=>'activityOrder',//地接社活动
            'Ticket_POI'=>'ticketOrder',//门票
            'Hotel'=>'hotelOrder',//酒店
            'Ticket_AIR'=>'airTicketOrder',//机票
            'FeaturedProduct'=>'activityOrder',//实物
            'StdActivity'=>'activityOrder',//活动
            'StdSelfDrive'=>'activityOrder',//自驾
        );
        if($orderType=='CarPool'){//拼车类型的订单
            if($isRefundCarPool){
                $url=$kbxToken->url.'/client/carpool/refundPersonalCarPoolOrder';
            }else{
                $url=$kbxToken->url.'/client/carpool/clientPay';
            }
        }elseif($orderType=='CustomMade'){//定制类型的订单
            // continue to do ... 准备退款定制类型的订单
            $url=$kbxToken->url.'/tripOrder/'.$data['id'].'/applyRefund';
        }else{
            $url=$kbxToken->url.'/client/'.$TypeArr[$orderType].'/createOrUpdate';
        }
        $token='Bearer '.$kbxToken->kbxToken();
        $list = json_encode($data);
        $res=$kbxToken->post_data($url,$list,$token);
        $res=$kbxToken->object_array($res);
        return $res;
    }
    //删除拼团订单
    public function deletePersonalCarPoolOrder($order_id)
    {
        $kbxToken = new KbxToken();
        $token='Bearer '.$kbxToken->kbxToken();
        $data = [
            "personalCarPoolOrderId"=>$order_id
        ];
        $url=$kbxToken->url.'/client/carpool/deletePersonalCarPoolOrder';
        $list = json_encode($data);
        $res=$kbxToken->post_data($url,$list,$token);
        $res=$kbxToken->object_array($res);
        return $res;
    }

    //删除定制订单
    public function deletePersonalCustomMadeOrder($order_id,$data=[])
    {
        $kbxToken = new KbxToken();
        $token='Bearer '.$kbxToken->kbxToken();
        $url=$kbxToken->url.'/tripOrder/'.$order_id.'/delete';
        $list = json_encode($data);
        $res=$kbxToken->post_data($url,$list,$token);
        $res=$kbxToken->object_array($res);

        return $res;
    }

    //查询分页订单列表
    public function kbx_order_by_page($page=1,$recordsPerPage=20,$post=array())
    {
        $kbxToken = new KbxToken();
        //查询订单list
        $url = $kbxToken->url . '/supplierOrder/listOrdersForPHP';
        $token = 'Bearer ' . $kbxToken->kbxToken();
        $url .= "?page=".$page."&recordsPerPage=".$recordsPerPage;

        //筛选
        $list = array();
        if(!empty($post)){
            if($post['order_no']!==''){
                $list['orderNo'] = $post['order_no'];
            }
            if($post['phone']!==''){
                $list['contactPhone'] = $post['phone'];
            }
            if($post['order_status']!==''){
                if($post['order_status']==5){
                    $list['orderStatus'] = $this->statusArr[2]['orderStatus'];
                    $list['paymentStatus'] = $this->statusArr[2]['paymentStatus'];
                    $list['refundStatus'] = 1;
                }else{
                    $list['orderStatus'] = $this->statusArr[$post['order_status']]['orderStatus'];
                    $list['paymentStatus'] = $this->statusArr[$post['order_status']]['paymentStatus'];
                }
            }
            if($post['goods_source']!==''){
                $list['typeSource'] = $post['goods_source']==1 ? 'myself' : 'viator';
            }
            if($post['creattime']!==''){
                $timrArr = explode("~",$post['creattime']);
                $list['startDate'] = $timrArr[0];
                $list['endDate'] = $timrArr[1];
            }
            if($post['travelDate']!==''){
                $travelTimeArr = explode("~",$post['travelDate']);
                $list['startTravelDate'] = $travelTimeArr[0];
                $list['endTravelDate'] = $travelTimeArr[1];
            }
        }

        $res = $kbxToken->post_data($url,json_encode($list),$token);
        $res = $kbxToken->object_array($res);
        $res = json_decode($res,true);
        //封装数据
        if(empty($res['returnedUserOrders'])){
            return [];
        }
        foreach($res['returnedUserOrders'] as $key=>$value){
            if($value['orderType']=="CarPool"){
                $res['returnedUserOrders'][$key]['id'] = $value['_id'];
                $res['returnedUserOrders'][$key]['typeSource'] = "myself";
                $res['returnedUserOrders'][$key]['goods']['goodsName'] = $value['carPoolOrder']['name']??"";
                $res['returnedUserOrders'][$key]['itinerary']['travelDate'] = $value['carPoolOrder']['details']['startDate']??"";
                $res['returnedUserOrders'][$key]['contact']['phone'] = $value['customer']['username']??"";
            }elseif($value['orderType']=="CustomMade"){
                $res['returnedUserOrders'][$key]['id'] = $value['_id'];
                $res['returnedUserOrders'][$key]['typeSource'] = "myself";
                $res['returnedUserOrders'][$key]['goods']['goodsName'] = $value['orderName']??"";
                $res['returnedUserOrders'][$key]['itinerary']['travelDate'] = $value['details']['startDate']??"";
                $res['returnedUserOrders'][$key]['contact']['phone'] = $value['consumer']['contact']['phone']??"";
                $res['returnedUserOrders'][$key]['payments']['originalMoney'] = $value['payments']['online']['amount'];
            }
        }
        return $res;
    }


    //使用order_no    查询订单
    public function kbx_order_by_no($orderNo)
    {
        $kbxToken = new KbxToken();
        $url = $kbxToken->url.'/supplierOrder/getOrderDetailByOrderNo/'.$orderNo;
        $token = 'Bearer ' . $kbxToken->kbxToken();
        $res = $kbxToken->get_data($url, $token);
        $res = $kbxToken->object_array($res);
        return $res;
    }


    //调用订单系统  查询订单接口  $member_id=159
    public function kbx_order_list($member_id)
    {
        $user = Db::name("member")->where('member_id',$member_id)->field("member_username")->find();
        $kbxToken = new KbxToken();
        //获取kbx的user_id
        $kbx = $kbxToken->kbxUser($user['member_username']);
        $kbx_id = $kbx['id'];

        //查询订单list
        $url=$kbxToken->url.'/client/users/'.$kbx_id.'/supplierOrders';
        $token='Bearer '.$kbxToken->kbxToken();
        $res=$kbxToken->get_data($url,$token);

        $res=$kbxToken->object_array($res);

        $dataArr = array();
        foreach ($res as $k=>$v){
            $data = array();
            $data['order_no']=$v['orderNo']??$v['orderId'];
            $data['order_id']=$v['id'];
            $data['orderType']=$v['orderType'];
            $data['isdelete']=0;
            $data['goods_name']=isset($v['name']) ? $v['name'] : '';
            $data['line_id']=isset($v['line']) ? $v['line'] : '';
            $data['goods_id']=isset($v['goods']['goodsId']) ? $v['goods']['goodsId'] : '';
            $data['person']=isset($v['orderPerson']) ? $v['orderPerson'] : '';
            $data['travel_date']=isset($v['startDate']) ? $v['startDate'] : '';
            $data['remarks']=isset($v['remarks']) ? $v['remarks'] : '';
            $data['fold_money']=isset($v['price']['amount']) ? $v['price']['amount'] : 0;
            $orderStatus = $v['orderStatusForUser'];//订单状态
            $paymentStatus = $v['status']['paymentStatus'];//支付状态
            $data['refund_status'] = isset($v['refundStatus']) ? $v['refundStatus'] : 0;
            $data['finished_condition'] = isset($v['finishedCondition']) ? $v['finishedCondition'] : 1;

            $data['order_status']= 1;
            if($orderStatus=='pending' || $orderStatus=='carpool' || $orderStatus=='notpay'){
                if($paymentStatus=='pending'){
                    $data['order_status']= 1;//待付款

                    $kbx_url=config('kbx_url');
                    $data['url']=$kbx_url.'/2cstatic/#/affirm-order?orderId='.$v['id'];
                }elseif($paymentStatus=='paid'){
                    $data['order_status']= 2;//已付款待使用
                }elseif($paymentStatus=='refunding'){
                    $data['order_status']= 5;//退款申请中
                }elseif($paymentStatus=='rejected'){
                    $data['order_status']= 9;//拒绝退款
                }
            }elseif($orderStatus=='toBeStarting'){
                if($paymentStatus=='paid'){
                    $data['order_status']= 2;//已付款待使用
                }elseif($paymentStatus=='refunding'){
                    $data['order_status']= 5;//退款申请中
                }elseif($paymentStatus=='rejected'){
                    $data['order_status']= 9;//拒绝退款
                }
            }elseif($orderStatus=='reviewed'){//已评价
                $data['order_status']= 4;
            }elseif($orderStatus=='finished'){//已使用待评价
                $data['order_status']= 3;
            }elseif($orderStatus=='canceled'){//已取消
                $data['order_status']= 6;
            }elseif($orderStatus=='expired'){//已过期
                $data['order_status']= 7;
            }elseif($orderStatus=='unknown'){//下单失败
                $data['order_status']= 10;
            }
            $initAt = strtotime($v['initAt']);
            $initAt = intval($initAt);
            $data['creattime'] = date("Y-m-d H:i:s",$initAt);

            if($data['orderType']=='Vehicle'){
                $data['types']='KBX';
            }

            $dataArr[$initAt] = $data;
        }

        return $dataArr;
    }


    //查询二次确认中的订单
    public function kbx_order_confirmation()
    {
        $kbxToken = new KbxToken();
        $url = $kbxToken->url.'/client/supplierOrder/pendingOrders';
        $token = 'Bearer ' . $kbxToken->kbxToken();
        $res = $kbxToken->get_data($url, $token);
        $res = $kbxToken->object_array($res);

        $resArr = array();
        foreach ($res as $k=>$v) {
            if(isset($v['subclassOrder']['details']['itemSummaries'])){
                $resArr[] = $v['subclassOrder'];
            }
        }

        return $resArr;
    }


    //订单系统调用接口
    //更新过期订单时，解放绑定的优惠券
    //http://h.kuaibangxing.com/api/kbx_order/CouponUnTying
    public function CouponUnTying(){
        $post = request()->post();
        if (!empty($post)) {
            //验证POST字段
            //secret密钥  secret_code约定字符串
            $match_arr = array("secret","secret_code","orderNo","memberId","couponType","costTicketId");
            $match_res = $this->match_post($match_arr,$post);
            if($match_res['code']==200){
                if($this->ApiValidate($post['secret_code'],$post['secret']))
                {//验证成功
                    if ($post['secret']=='' || $post['secret_code']=='' || $post['orderNo']=='' || $post['memberId']=='' || $post['couponType']=='' || $post['costTicketId']=='') {
                        $this->error("字段不能为空",array(),415);
                    }
                    if ($post['couponType']=='KBX'){
                        $Kbxcoupon=  new Kbxcoupon();
                        $res = $Kbxcoupon->refundCashCoupon($post['memberId'],$post['costTicketId'],$post['orderNo']);
                    }else{
                        $res = db('coupondetails')->where('id',$post['costTicketId'])->update(['usestatus'=>0]);
                    }
                    if(!$res['msg']){
                        $this->success("解绑成功",$res,200);
                    }else{
                        $this->error("解绑失败",$res,417);
                    }
                }else{
                    $this->error("密令错误",array(),412);
                }
            }else{
                $this->error("POST字段缺少",array('missKey'=>$match_res['missKey']),$match_res['code']);
            }
        }else{
            $this->error("无数据传入",array(),413);
        }
    }


    //用户的用车/接送机优惠券列表
    // 暂定接送机 304  包车305
    public function CouponCar(){
        $post = request()->post();
        if (!empty($post)) {
            //验证POST字段
            //secret密钥  secret_code约定字符串
            $match_arr = array("secret","secret_code","member_username","type");
            $match_res = $this->match_post($match_arr,$post);
            if($match_res['code']==200){
                if($this->ApiValidate($post['secret_code'],$post['secret']))
                {//验证成功
                    $memberIdinfo=Db::name('member')->where(['member_phone'=>$post['member_username']])->find();
                    if(empty($memberIdinfo)){
                        $this->error("member_username不存在",array(),417);
                    }else{
                        $memberId=$memberIdinfo['member_id'];
                    }
                    if($post['type'] == 'airport'){
                        $classify_id=304;
                    }elseif ($post['type'] == 'car'){
                        $classify_id=305;
                    }else{
                        $this->error("type参数错误",array(),417);
                    }
//                    $data=Db::name('coupondetails')->alias('cds')
//                        ->join('coupon cp','cds.coupon_id = cp.coupon_id')
//                        ->where(['cds.member_id'=>$memberId,'cds.usestatus'=>0])
//                        ->select();
                    $data=Db::name('coupondetails')
                        ->where(['member_id'=>$memberId,'usestatus'=>0])
                        ->select();
                    $datalist=[];

                    if(!empty($data)){
                        foreach ($data as $k){
                            $res=Db::name('coupon')->where(['coupon_id'=>$k['coupon_id']])->find();
                            if(empty($res['classify_id'])){
                                continue;
                            }
                            $res['id']=$k['id'];
                            $classify_id_list=explode(',',$res['classify_id']);
                            if (in_array($classify_id,$classify_id_list) || $classify_id_list[0] == 999999){
                                $datalist[]=$res;
                            }
                        }
                    }

                    $this->success("获取数据成功",$datalist,200);
                }else{
                    $this->error("密令错误",array(),412);
                }
            }else{
                $this->error("POST字段缺少",array('missKey'=>$match_res['missKey']),$match_res['code']);
            }
        }else{
            $this->error("无数据传入",array(),413);
        }
    }

    //用车/接送机优惠券使用
    public function useCouponCar(){
        $post = request()->post();
        if (!empty($post)) {
            //验证POST字段
            //secret密钥  secret_code约定字符串
            $match_arr = array("secret","secret_code","member_username","Id","orderId","createtime");
            $match_res = $this->match_post($match_arr,$post);
            if($match_res['code']==200){
                if($this->ApiValidate($post['secret_code'],$post['secret']))
                {//验证成功
                    $memberIdinfo=Db::name('member')->where(['member_phone'=>$post['member_username']])->find();
                    if(empty($memberIdinfo)){
                        $this->error("member_username不存在",array(),417);
                    }else{
                        $memberId=$memberIdinfo['member_id'];
                    }

                    //验证该优惠券是否使用
                    $coupon_status=Db::name('coupondetails')->where(['id'=>$post['Id'],'member_id'=>$memberId,'usestatus'=>0])->find();
                    if(empty($coupon_status)){
                        $this->error("该旅行红包已使用或不存在",array(),417);
                    }
                    $list_coupon_use=[
                        'coupon_id'=>$post['Id'],
                        'member_id'=>$memberId,
                        'order_id'=>$post['orderId'],
                        'createtime'=>$post['createtime'],
                    ];
                    Db::startTrans();
                    try{
                        Db::name('coupondetails')->where(['id'=>$post['Id']])->update(['usestatus'=>1,'usetime'=>$post['createtime']]);
                        Db::name('coupon_log')->insert($list_coupon_use);
                        Db::commit();
                        $this->success("保存数据成功",array(),200);
                    }catch (Exception $e){
                        Db::rollback();
                        $this->error("保存数据失败",array(),417);
                    }
                }else{
                    $this->error("密令错误",array(),412);
                }
            }else{
                $this->error("POST字段缺少",array('missKey'=>$match_res['missKey']),$match_res['code']);
            }
        }else{
            $this->error("无数据传入",array(),413);
        }
    }


    //【测试使用】使用order_no    查询订单
    public function test_kbx_order_by_no($orderNo='STF35247')
    {
        $kbxToken = new KbxToken();
        $url = $kbxToken->url.'/supplierOrder/getOrderDetailByOrderNo/'.$orderNo;
        $token = 'Bearer ' . $kbxToken->kbxToken();
        $res = $kbxToken->get_data($url, $token);
        $res = $kbxToken->object_array($res);

        echo "<pre>";
        var_dump($res);
        echo "</pre>";
        exit;

        return $res;
    }


    //订单详情接口  个人中心
    public function kbxOrderDetail()
    {
        $post = request()->request();
        $orderNo = $post['order_no'];
        $member_id = $post['member_id'];

        $order = db("order")->where("order_no",$orderNo)->find();
        if(!empty($order))
        {//mysql
            $res = $this->formatOrder($order,2);
        }else{//mongo
            $kbxToken = new KbxToken();
            $member = db("member")->where("member_id",$member_id)->field("member_username")->find();
            $user = $kbxToken->kbxUser($member['member_username']);
            if(empty($user['id'])){
                $shu=[
                    'code'=>400,
                    'msg'=>'找不到user',
                ];
                return json_encode($shu);
            }

            $url = $kbxToken->url.'/client/users/'.$user['id'].'/getOrderDetailByOrderNo/'.$orderNo;
            $token = 'Bearer ' . $kbxToken->kbxToken();
            $res = $kbxToken->get_data($url, $token);
            $res = $kbxToken->object_array($res);
            if($res['orderType']=='Vehicle'){//用车订单

            }elseif($res['orderType']=='CarPool'){//拼团订单
                $res = $this->formatOrder($res,3);
            }elseif($res['orderType']=='CustomMade'){//定制订单
                $res = $this->formatOrder($res,4);
            }else{
                $res = $this->formatOrder($res,1);
            }
        }

        $shu=[
            'code'=>0,
            'msg'=>'',
            'data'=>$res
        ];

        return json_encode($shu);
    }


    //获取显示的订单状态
    public function getDisplayOrderStateTitle($orderStatus,$paymentStatus)
    {
        $displayedStatusStr= '待付款';
        if($orderStatus=='pending' ||$orderStatus=='carpool'){
            if($paymentStatus=='pending'){
                $displayedStatusStr= '待付款';//待付款
            }elseif($paymentStatus=='paid'){
                $displayedStatusStr= '已付款待使用';//已付款待使用
            }elseif($paymentStatus=='refunding'){
                $displayedStatusStr= '退款申请中';//退款申请中
            }elseif($paymentStatus=='rejected'){
                $displayedStatusStr= '拒绝退款';//拒绝退款
            }
        }elseif($orderStatus=='toBeStarting'){
            if($paymentStatus=='paid'){
                $displayedStatusStr= '已付款待使用';//已付款待使用
            }elseif($paymentStatus=='refunding'){
                $displayedStatusStr= '退款申请中';//退款申请中
            }elseif($paymentStatus=='rejected'){
                $displayedStatusStr= '拒绝退款';//拒绝退款
            }
        }elseif($orderStatus=='reviewed'){//已评价
            $displayedStatusStr= '已评价';
        }elseif($orderStatus=='finished'){//已使用待评价
            $displayedStatusStr= '已使用待评价';
        }elseif($orderStatus=='canceled'){//已取消
            if($paymentStatus=='refunded'){
                $displayedStatusStr= '已退款';//已退款
            }else{
                $displayedStatusStr= '已取消';
            }
        }elseif($orderStatus=='expired'){//已过期
            $displayedStatusStr= '已过期';
        }elseif($orderStatus=='unknown'){//下单失败
            $displayedStatusStr= '下单失败';
        }

        return $displayedStatusStr;
    }

    //未支付订单详情接口
    public function kbxRepeatOrderDetail()
    {
        $post = request()->request();
        $orderNo = $post['order_no'];

        $order = db("order")->where("order_no",$orderNo)->find();
        if(!empty($order))
        {//mysql
            $resOrder = $this->formatOrder($order,2);
        }else{//mongo
            $kbxToken = new KbxToken();
            $res = $this->kbx_order_by_no($orderNo);
            $res = $kbxToken->object_array($res);
            //判断状态
            $orderStatus = $res['status']['orderStatus'];
            $paymentStatus = $res['status']['paymentStatus'];
            $displayedStatusStr = $this->getDisplayOrderStateTitle($orderStatus,$paymentStatus);

            $resOrder = [];
            if(in_array($res['orderType'],['CarPool'])){
                $resOrder['order_id'] = $res['_id']??"";
                $resOrder['orderNo'] = $res['orderNo'];
                $resOrder['orderName'] = $res['carPoolOrder']['name'];
                $resOrder['orderType'] = $res['orderType'];
                $resOrder['cityName'] = $res['carPoolOrder']['details']['fromCity']['name'];
                $resOrder['displayedStatusStr'] = $displayedStatusStr;
                $resOrder['isdelete'] = isset($res['isDelete']) ? $res['isDelete'] : 0;
                $resOrder['initAt'] = "北京时间".date("Y-m-d H:i:s",strtotime($res['createdAt']));
                $resOrder['foldMoney'] = $res['payments']['foldMoney'];
                $resOrder['orderuser'] = [
                    "Phone"=>$res['customer']['username'],
                    "email"=>$res['customer']['email']??"",
                    "firstname"=>$res['customer']['profile']['name'],
                    "surname"=>'',
                ];
                $resOrder['travelDate'] = $res['carPoolOrder']['details']['startDate'];
                $resOrder['username'] = $res['customer']['profile']['name'];
                $resOrder['userphone'] = $res['customer']['username'];
                $resOrder['email'] = $res['customer']['email']??"";
                $resOrder['serveAddress'] = $res['serveAddress']??"";
                $resOrder['carPoolOrder'] = $res['carPoolOrder']??[];
            }else{
                $resOrder['orderNo'] = $res['orderNo'];
                $resOrder['orderId'] = $res['orderId']??$res['orderNo'];
                $resOrder['orderName'] = $res['goods']['goodsName']??($res['orderName']??"");
                $resOrder['goodsId'] = $res['goods']['goodsId']??0;
                $resOrder['orderType'] = $res['orderType'];
                $resOrder['cityName'] = $res['goods']['fromCity']['name']??($res['details']['fromCity']['name']??"");
                $resOrder['displayedStatusStr'] = $displayedStatusStr;
                $resOrder['typeSource'] = $res['typeSource'];
                $resOrder['speedStatus'] = $res['speedStatus']??0;//默认不需要二次确认
                $resOrder['isdelete'] = isset($res['isDelete']) ? $res['isDelete'] : 0;
                $resOrder['initAt'] = "北京时间".date("Y-m-d H:i:s",strtotime($res['initAt']));
                $resOrder['travelDate'] = $res['itinerary']['travelDate']??($res['details']['startDate']??'');
                $resOrder['gradeName'] = $res['goods']['gradeName']??"";
                $resOrder['orderPerson'] = $res['itinerary']['orderPerson']??'';
                $resOrder['orderuser'] = isset($res['itinerary']['orderSubsidiary']['orderuser'])?$res['itinerary']['orderSubsidiary']['orderuser']:'';
                if(empty($resOrder['orderuser'])){
                    $resOrder['orderuser'] = [
                        "Phone"=>$res['booker']['user']['username']??($res['consumer']['contact']['phone']??''),
                        "email"=>$res['booker']['user']['email']??($res['consumer']['contact']['email']??''),
                        "firstname"=>$res['booker']['user']['profile']['name']??($res['consumer']['contact']['name']??''),
                        "surname"=>'',
                    ];
                }
                $resOrder['originalMoney'] = $res['payments']['originalMoney']??$res['payments']['online']['amount'];
                $resOrder['bandiduser'] = isset($res['itinerary']['orderSubsidiary']['bandiduser'])?$res['itinerary']['orderSubsidiary']['bandiduser']:'';
                $resOrder['foldMoney'] = $res['payments']['foldMoney']??$res['payments']['online']['amount'];
                $resOrder['remarks'] = $res['contact']['remarks']??($res['consumer']['contact']['remarks']??'');
                $resOrder['serveAddress'] = $res['contact']['serveAddress']??($res['consumer']['contact']['serveAddress']??'');
            }


            //汇率
            $exchangeArr = Db::name("exchange")->select();
            if(!empty($exchangeArr)){
                $moneyArr = array();
                foreach ($exchangeArr as $k=>$v) {
                    $v_money = $resOrder['foldMoney']/$v['exchange_rate'];
                    $v_money = ceil($v_money*100)/100;
                    $moneyArr[] = array("code"=>$v['currency_code'],"money"=>$v_money);
                }
            }
            $moneyArr[] = array("code"=>"CNY","money"=>$resOrder['foldMoney']);
            $resOrder['moneyArr'] = $moneyArr;
        }

        $shu=[
            'code'=>0,
            'msg'=>'',
            'data'=>$resOrder
        ];

        return json_encode($shu);
    }

    //订单字段格式统一
    public function formatOrder($order,$type=1)
    {
        //$type==1为monggo订单，$type==2位mysql订单
        $resOrder = array();
        if($type==1){
            $city = db("city")->where("kbx_id",$order['fromCity'])->find();
            $resOrder['orderId'] = $order['subclassOrder']['id'];
            $resOrder['orderNo'] = $order['subclassOrder']['orderNo'];
            $resOrder['orderName'] = $order['name'];
            $resOrder['goodsId'] = isset($order['subclassOrder']['goods']['goodsId']) ? $order['subclassOrder']['goods']['goodsId'] : '';
            $resOrder['orderType'] = $order['orderType'];
            $resOrder['cityName'] = isset($city['name']) ? $city['name'] : '';
            $resOrder['displayedStatusStr'] = $order['displayedStatusStr'];
            $resOrder['typeSource'] = $order['subclassOrder']['typeSource'];
            $resOrder['speedStatus'] = $order['subclassOrder']['speedStatus'];
            $resOrder['isdelete'] = isset($order['subclassOrder']['isDelete']) ? $order['subclassOrder']['isDelete'] : 0;
            $resOrder['initAt'] = "北京时间".date("Y-m-d H:i:s",strtotime($order['subclassOrder']['initAt']));
            $resOrder['travelDate'] = $order['subclassOrder']['itinerary']['travelDate'];
            $resOrder['gradeName'] = isset($order['subclassOrder']['goods']['gradeName']) ? $order['subclassOrder']['goods']['gradeName'] : '';
            $resOrder['orderPerson'] = $order['subclassOrder']['itinerary']['orderPerson'];
            $resOrder['orderuser'] = isset($order['subclassOrder']['itinerary']['orderSubsidiary']['orderuser'])?$order['subclassOrder']['itinerary']['orderSubsidiary']['orderuser']:'';
            $resOrder['bandiduser'] = isset($order['subclassOrder']['itinerary']['orderSubsidiary']['bandiduser'])?$order['subclassOrder']['itinerary']['orderSubsidiary']['bandiduser']:'';
            $resOrder['originalMoney'] = $order['subclassOrder']['payments']['originalMoney'];
            $resOrder['foldMoney'] = $order['subclassOrder']['payments']['foldMoney'];
            $resOrder['remarks'] = isset($order['subclassOrder']['contact']['remarks'])?$order['subclassOrder']['contact']['remarks']:'';
            $resOrder['serveAddress'] = isset($order['subclassOrder']['contact']['serveAddress'])?$order['subclassOrder']['contact']['serveAddress']:'';
        }elseif($type==3){
            $resOrder['orderId'] = $order['id'];
            $resOrder['orderNo'] = $order['orderId'];
            $resOrder['orderName'] = $order['name'];
            $resOrder['goodsId'] = '';
            $resOrder['orderType'] = $order['orderType'];
            $resOrder['cityName'] = '';
            $resOrder['displayedStatusStr'] = $order['displayedStatusStr'];
            $resOrder['typeSource'] = 'myself';
            $resOrder['speedStatus'] = 0;
            $resOrder['isdelete'] = 0;
            $resOrder['initAt'] = "北京时间".date("Y-m-d H:i:s",strtotime($order['initAt']));
            $resOrder['travelDate'] = $order['startDate'];
            $resOrder['gradeName'] = '';
            $resOrder['orderPerson'] = [];
            $resOrder['orderuser']['Phone'] = isset($order['subclassOrder']['customer']['username'])?$order['subclassOrder']['customer']['username']:'';
            $resOrder['orderuser']['email'] = isset($order['subclassOrder']['customer']['email'])?$order['subclassOrder']['customer']['email']:'';
            $resOrder['orderuser']['surname'] = isset($order['subclassOrder']['customer']['profile']['name'])?$order['subclassOrder']['customer']['profile']['name']:'';
            $resOrder['bandiduser'] = '';
            $resOrder['originalMoney'] = $order['price']['amount'];
            $resOrder['foldMoney'] = $order['price']['amount'];
            $resOrder['remarks'] = '';
            $resOrder['serveAddress'] = isset($order['subclassOrder']['serveAddress'])?$order['subclassOrder']['serveAddress']:'';
        }elseif($type==4){
            $resOrder['orderId'] = $order['id'];
            $resOrder['orderNo'] = $order['orderNo'];
            $resOrder['orderName'] = $order['name'];
            $resOrder['goodsId'] = $order['tripId'];
            $resOrder['orderType'] = $order['orderType'];
            $resOrder['cityName'] = $order['fromCity']['name']??'';
            $resOrder['displayedStatusStr'] = $order['displayedStatusStr'];
            $resOrder['typeSource'] = 'myself';
            $resOrder['speedStatus'] = 0;
            $resOrder['isdelete'] = isset($order['isDelete']) ? $order['isDelete'] : 0;
            $resOrder['initAt'] = "北京时间".date("Y-m-d H:i:s",strtotime($order['initAt']));
            $resOrder['travelDate'] = $order['startDate'];
            $resOrder['gradeName'] = '';
            $resOrder['orderPerson'] = '';
            $resOrder['orderuser'] = [
                "Phone"=>$order['booker']['user']['username']??($order['consumer']['contact']['phone']??''),
                "email"=>$order['booker']['user']['email']??($order['consumer']['contact']['email']??''),
                "firstname"=>$order['booker']['user']['profile']['name']??($order['consumer']['contact']['name']??''),
                "surname"=>'',
            ];
            $resOrder['bandiduser'] = '';
            $resOrder['originalMoney'] = $order['price']['amount'];
            $resOrder['foldMoney'] = $order['price']['amount'];
            $resOrder['remarks'] = '';
            $resOrder['serveAddress'] = '';
        }else{
            $goods = db("goods")->where("goods_id",$order['goods_id'])->find();
            $city = db("city")->where("id",$goods['city_id'])->find();
            $orderSubsidiary = json_decode($order['order_subsidiary'],true);
            $statusArr = array(1=>'待付款',2=>'已付款待使用',3=>'已使用待评价',4=>'已评价',5=>'退款申请中',6=>'已取消',7=>'已过期',8=>'已退款',9=>'拒绝退款',10=>'下单失败');

            $resOrder['orderId'] = $order['order_id'];
            $resOrder['orderNo'] = $order['order_no'];
            $resOrder['goodsId'] = $goods['goods_id'];
            $resOrder['orderName'] = $goods['goods_name'];
            $resOrder['orderType'] = $goods['orderType'];
            $resOrder['cityName'] = $city['name'];
            $resOrder['displayedStatusStr'] = $statusArr[$order['order_status']];
            $resOrder['typeSource'] = $order['typesource'];
            $resOrder['speedStatus'] = $order['speedstatus'];
            $resOrder['isdelete'] = $order['isdelete'];
            $resOrder['initAt'] = "北京时间".date("Y-m-d H:i:s",$order['creattime']);
            $resOrder['travelDate'] = $order['travel_date'];
            $resOrder['gradeName'] = $order['grade_name'];
            $resOrder['orderPerson'] = json_decode($order['orderperson'],true);
            $resOrder['orderuser'] = isset($orderSubsidiary['orderuser']) ? $orderSubsidiary['orderuser'] : '';//下单人信息
            $resOrder['bandiduser'] = isset($orderSubsidiary['bandiduser']) ? $orderSubsidiary['bandiduser'] : '';
            $resOrder['originalMoney'] = $order['original_money'];
            $resOrder['foldMoney'] = $order['fold_money'];
            $resOrder['remarks'] = isset($order['remarks']) ? $order['remarks'] : '';
            $resOrder['serveAddress'] = isset($order['serve_address']) ? $order['serve_address'] : '';
        }

        //汇率
        $exchangeArr = Db::name("exchange")->select();
        if(!empty($exchangeArr)){
            $moneyArr = array();
            foreach ($exchangeArr as $k=>$v) {
                $v_money = $resOrder['foldMoney']/$v['exchange_rate'];
                $v_money = ceil($v_money*100)/100;
                $moneyArr[] = array("code"=>$v['currency_code'],"money"=>$v_money);
            }
        }
        $moneyArr[] = array("code"=>"CNY","money"=>$resOrder['foldMoney']);
        $resOrder['moneyArr'] = $moneyArr;

        return $resOrder;
    }


    //包车接送机获取折扣
    public function getDiscoun(){
        $post = request()->post();
        if (!empty($post)) {
            //验证POST字段
            //secret密钥  secret_code约定字符串
            $match_arr = array("secret","secret_code","username","type");//type=1 包车，type=2 接送机
            $match_res = $this->match_post($match_arr,$post);
            if($match_res['code']==200){
                if($this->ApiValidate($post['secret_code'],$post['secret']))
                {//验证成功
                    if ($post['secret']=='' || $post['secret_code']=='' || $post['username']=='' || $post['type']=='') {
                        $this->error("字段不能为空",array(),415);
                    }
                    $username = $post['username'];
                    $type = $post['type'];
                    if($type==1){
                        $classiftId = 305;
                    }else{
                        $classiftId = 304;
                    }
                    $member = Db::name("member")->where("member_username",$username)->field("member_type_id")->find();
                    if(!empty($member)){
                        $memberTypeId = $member['member_type_id'];
                        $per = 1;
                        if($memberTypeId > 1){
                            $discoun = Db::name("member_type")->where("member_type_id",$memberTypeId)->field("discoun_per_list")->find();
                            $discoun_per_list = $discoun['discoun_per_list'];
                            if($discoun_per_list && $discoun_per_list!==''){
                                $discoun_per_arr = explode(",",$discoun_per_list);
                                foreach ($discoun_per_arr as $per_value){
                                    $per_arr = explode("_",$per_value);
                                    $per_classify_id = $per_arr[0];
                                    if($per_classify_id==$classiftId){
                                        $per = $per_arr[1];
                                        break;
                                    }
                                }
                            }else{
                                $this->success("该会员等级未设置折扣",array("discoun_per"=>1),417);
                            }
                        }else{
                            $this->success("普通用户不享受折扣",array("discoun_per"=>1),417);
                        }
                        $this->success("查询成功",array("discoun_per"=>$per),200);
                    }else{
                        $this->error("未找到该用户",array(),417);
                    }
                }else{
                    $this->error("密令错误",array(),412);
                }
            }else{
                $this->error("POST字段缺少",array('missKey'=>$match_res['missKey']),$match_res['code']);
            }
        }else{
            $this->error("无数据传入",array(),413);
        }
    }



    //查询客户订单 接口
    public function kbx_custom_order()
    {
        $post = request()->request();
        $member_id = $post['member_id'];
        $kbxToken = new KbxToken();
        $member = db("member")->where("member_id",$member_id)->field("member_username")->find();
        $user = $kbxToken->kbxUser($member['member_username']);
        if(empty($user['id'])){
            $shu=[
                'code'=>400,
                'msg'=>'找不到user',
            ];
            return json_encode($shu);
        }

        $url = $kbxToken->url.'/corders/listOrders4User/'.$user['id'];

        $token = 'Bearer ' . $kbxToken->kbxToken();
        $res = $kbxToken->get_data($url, $token);
        $res = $kbxToken->object_array($res);
        //插入当日明日的天气状况
        $today = time();//当天时间戳
        $yesterday = $today-86400;//昨天时间戳
        $third_day = $today+86400+86400;//后天时间戳

        $weather_date = cache('Weather');
        $weather_arr = array();
        foreach ($weather_date as $item) {
            if(isset($item['kbx_id']) && $item['kbx_id']!==''){
                $weather_arr[$item['kbx_id']] = $item;
            }
        }

        $articleArr = array();//存放已推送的文章id
        foreach ($res['orders'] as $key=>$value) {
            if (empty($value['dateOrderGroups'])) {
                continue;
            }
            foreach ($value['dateOrderGroups'] as $date_key => $date_value) {
                if (!isset($date_value['date'])) {
                    continue;
                }
                $date = strtotime($date_value['date']);
                foreach ($date_value['currentDateOrders'] as $k => $v) {
                    if (empty($v['fromCity'])) {
                        continue;
                    }
                    $cityId = $v['fromCity']['_id'];

                    $article_bind = [];
                    if (!empty($member_id)) {
                        $article_bind = db("article_binduser")->where('member_id', $member_id)->find();
                    }
                    if (!empty($article_bind['article_id']) && !in_array($article_bind['article_id'], $articleArr)) {
                        $article_id = $article_bind['article_id'];
                    } else {
                        //插入攻略
                        $article_id = $this->getArticle($cityId, $v['orderType'], $articleArr);
                    }

                    if ($article_id > 0) {
                        $articleArr[] = $article_id;
                        $article = db("article")
                            ->alias('a')
                            ->join('attachment t', 'a.thumb=t.id', 'left')
                            ->where("a.id", $article_id)
                            ->field("a.id,a.title,t.filepath")
                            ->find();
                        $res['orders'][$key]['dateOrderGroups'][$date_key]['currentDateOrders'][$k]['article'] = $article;
                    }

                    if ($yesterday <= $date && $date <= $third_day) {
                        if (isset($weather_arr[$cityId])) {//符合日期
                            if (!isset($weather_arr[$cityId]['daily_forecast'][1])) {
                                continue;
                            }

                            //改为明天
                            $res['orders'][$key]['dateOrderGroups'][$date_key]['currentDateOrders'][$k]['fromCity']['weather'] = $weather_arr[$cityId]['daily_forecast'][1];

//                            foreach ($weather_arr[$cityId]['daily_forecast'] as $w_value) {
//                                if ($date_value['date'] == $w_value['date']) {
//                                    $res['orders'][$key]['dateOrderGroups'][$date_key]['currentDateOrders'][$k]['fromCity']['weather'] = $w_value;
//                                }
//                            }
                        }
                    }
                }
            }
        }

        $shu=[
            'code'=>0,
            'msg'=>'',
            'data'=>$res
        ];

        return json_encode($shu);
    }




    //行程打分 接口
    public function kbx_grade_custom_order()
    {
        $post = request()->request();
        $member_id = $post['member_id'];
        $currentDateOrderId = $post['order_id'];
        $data = json_decode($post['rates'],true);

        $kbxToken = new KbxToken();
        $member = db("member")->where("member_id",$member_id)->field("member_username")->find();
        $user = $kbxToken->kbxUser($member['member_username']);
        if(empty($user['id'])){
            $shu=[
                'code'=>400,
                'msg'=>'找不到user',
            ];
            return json_encode($shu);
        }

        $url = $kbxToken->url.'/sorders/setRatesById/'.$currentDateOrderId;
        $token = 'Bearer ' . $kbxToken->kbxToken();
        $list = json_encode(['rates'=>$data]);
        $res = $kbxToken->post_data($url,$list,$token);

        $res = json_decode($res,true);
        if(isset($res['_id'])){
            $shu=[
                'code'=>0,
                'msg'=>'',
                'data'=>$res
            ];
        }else{
            $shu=[
                'code'=>401,
                'msg'=>'打分出错',
                'data'=>$res
            ];
        }

        return json_encode($shu);
    }




    //按照城市和订单类型，获取随机推送文章      $oldArr：已推送过的文章id数组
    public function getArticle($kbx_id='583ad6a8b7bd9f6ebf150444',$orderType='Hotel',$oldArr=array()){
        $city = db("city")->where("kbx_id",$kbx_id)->field("id")->find();

        if(empty($city)){
            return 0;
        }

        $city_id = $city['id'];
        $where['status'] = 1;
        $city_where = 'FIND_IN_SET('.$city_id.',city_id) or city_id=999999';
        $orderType_where = 'FIND_IN_SET("'.$orderType.'",orderType) or orderType=999999';
        $article = db("article")
            ->where($where)
            ->where($city_where)
            ->where($orderType_where)
            ->field("id")
            ->select();

        if(!empty($article)){
            $resArr = array();
            if(!empty($oldArr)){
                foreach ($article as $k=>$v) {
                    if(!in_array($v['id'],$oldArr)){
                        $resArr[] = $v;
                    }
                }
            }else{
                $resArr = $article;
            }
            if(!empty($resArr)){
                //随机抽选一个
                $keys = array_keys($resArr);
                shuffle($keys);
                $key = array_pop($keys);

                return $resArr[$key]['id'];
            }else{
                return 0;
            }

        }else{
            return 0;
        }
    }

    //定制行程的商机录入（对接订单系统接口）
    /**
     * @param $data array 以下是简版参数(数据均可为空)
     * $data = [
     *  "name"=>"测试用户",
     *  "phone"=>"17700001111",
     *  "from_kbx_id"=>"583ad6a8b7bd9f6ebf150447",//对应mongo的城市id
     *  "adultNum"=>"5",
     *  "startDate"=>"2019-05-01",
     *  "days"=>"5",
     * ];
     * @return string
     */
    public function enterBusOpportunities($data)
    {
        $kbxToken = new KbxToken();
        $token = 'Bearer ' . $kbxToken->kbxToken();
        $url = $kbxToken->url."/opportunityByClient";
        $post_data = [
            "customer"=>[//客户信息
                "name"=>isset($data['nickname'])?$data['nickname']:"",//客户姓名
                "phone"=>isset($data['phone'])?$data['phone']:"",//客户电话
                "wechat"=>isset($data['wechat'])?$data['wechat']:"",//客户微信号
                "email"=>isset($data['email'])?$data['email']:"",//客户邮箱
                "sex"=>isset($data['sex'])?$data['sex']:"",//客户性别
                "age"=>isset($data['age'])?$data['age']:"",//客户年龄
                "ageBand"=>isset($data['ageBand'])?$data['ageBand']:"",//客户年龄范围
                "description"=>isset($data['description'])?$data['description']:"",//客户描述
            ],
            "tripDemand"=>[//出行信息
                "startCity"=>isset($data['startCity'])?$data['startCity']:"",//出发城市名称
                "fromCity"=>isset($data['from_kbx_id'])?$data['from_kbx_id']:"",//目的地城市mongo_id
                "startDate"=>isset($data['start_go_time'])?$data['start_go_time']:"",//出行日期
                "days"=>isset($data['days'])?$data['days']:"",//出行天数
                "adultPassengers"=>isset($data['adult'])?$data['adult']:0,//出行成人人数
                "childPassengers"=>isset($data['child'])?$data['child']:0,//出行儿童人数
                "bigGroup"=>isset($data['bigGroup'])?$data['bigGroup']:false,//出行类型 团体true 个人false
                "note"=>isset($data['note'])?$data['note']:"",//备注
            ],
            "origin"=>isset($data['source'])?$data['source']:"",//来源平台
            "receiveDate"=>isset($data['receiveDate'])?$data['receiveDate']:"",//接待时间
            "paid"=>isset($data['paid'])?$data['paid']:false,//是否支付
            "tripName"=>isset($data['name'])?$data['name']:'',//行程标题
            "fFromTrip"=>true,//是否来源定制系统
            "priceDescription"=>[
                "tips"=>isset($data['price_trips'])?$data['price_trips']:"",//费用特别说明
                "included"=>isset($data['price_included'])?$data['price_included']:"",//费用包含
                "excluded"=>isset($data['price_excluded'])?$data['price_excluded']:""//费用不含
            ],
        ];
        //若传递_id参数 表示更新此商机 若无 则代表新增
        if(isset($data['opportunity_id']) && !empty($data['opportunity_id'])){
            $post_data['_id'] = $data['opportunity_id'];
        }
        $list = json_encode($post_data);
        $res=$kbxToken->post_data($url,$list,$token);
        $res=$kbxToken->object_array($res);
        $result = json_decode($res,true);
//        var_dump($result);
        if(isset($result['_id']) && !empty($result['_id'])){
            return $result['_id'];//录入商机成功
        }else{
            return "";//录入商机失败
        }
    }

    //订单加人接口
    public function addCustomerByMall($post_data,$order_data=[])
    {
        $mem=db('member')->where('member_id',$post_data['member_id'])->field('member_username,member_pcode,kbx_id')->find();
        $kbxToken = new KbxToken();
        $url = $kbxToken->url.'/carpool/addCustomerByMall';
        $token = 'Bearer ' . $kbxToken->kbxToken();
        $data = [
            "personalOrder"=>[
                "carPoolOrder"=>$post_data['carPoolOrder']??"",//拼团订单id
                "paid"=>false,//是否支付
                "origin"=>"WechatOA",
                "otaOrderId"=>"",
                "note"=> $post_data['note']??"",//备注
                "serveAddress"=>$post_data['serveAddress']??"",//酒店地址
                'booker'=> [//预订人
                    "username" => $mem['member_username'],
                    "memberId" => $post_data['member_id'],//会员id
                    "memberPCode" => !empty($mem['member_pcode'])?$mem['member_pcode']:null,//推荐人id
                    "userId"=>$mem['kbx_id'],
                ],
                "consumer"=>[
                    'contact'=>[
                        "name"=> $post_data['consumer_name']??"",//客户姓名
                        "phone"=>$post_data['consumer_phone']??"",//客户手机号
                        "wechat"=>$post_data['consumer_wechat']??"",//客户微信号
                        "email"=>$post_data['consumer_email']??"",//客户邮箱
                    ]
                ],
                "adultPassengers"=>$post_data['adultPassengers']??"0",//成人人数
                "childPassengers"=>$post_data['childPassengers']??"0",//儿童人数
                "childAges"=>$post_data['childAges']??[],//儿童年龄数组
                "largeLuggages"=>$post_data['largeLuggages']??"0",//行李数量
                "hotelRoomNum"=>$post_data['hotel_num']??"0",//行李数量
                "price"=>[
                    'currency'=>"CNY",//拼团价格单位
                    'amount'=>$post_data['amount']??"",//拼团价格
                ]
            ]
        ];
        if(!empty($order_data)){
            unset($data['personalOrder']['carPoolOrder']);
            $data['order'] = $order_data;
        }
        $list = json_encode($data);
//        var_dump($list);exit;
        $res=$kbxToken->post_data($url,$list,$token);
        //记录请求的数据
        trace($url);trace($list);trace($token);trace($res);

        $res=$kbxToken->object_array($res);
        //error
        //{
        //    "msg": "缺省客户手机号码或姓名信息!"
        //}
        //success
        //{
        //    '_id':'xxxxxxxxx',
        //    ...
        //}
        return json_decode($res,true);
    }

    //查询客户订单 调试
    public function show_kbx_custom_order()
    {
        $member_id = '3295';
        $kbxToken = new KbxToken();
        $member = db("member")->where("member_id",$member_id)->field("member_username")->find();
        $user = $kbxToken->kbxUser($member['member_username']);
        if(empty($user['id'])){
            $shu=[
                'code'=>400,
                'msg'=>'找不到user',
            ];
            return json_encode($shu);
        }

        $url = $kbxToken->url.'/corders/listOrders4User/'.$user['id'];
        $token = 'Bearer ' . $kbxToken->kbxToken();
        $res = $kbxToken->get_data($url, $token);
        $res = $kbxToken->object_array($res);
        //插入当日明日的天气状况
        $today = time();//当天时间戳
        $yesterday = $today-86400;//昨天时间戳
        $third_day = $today+86400+86400;//后天时间戳

        $weather_date = cache('Weather');
        $weather_arr = array();
        foreach ($weather_date as $item) {
            if(isset($item['kbx_id']) && $item['kbx_id']!==''){
                $weather_arr[$item['kbx_id']] = $item;
            }
        }

        $articleArr = array();//存放已推送的文章id
        foreach ($res['orders'] as $key=>$value) {
            if (empty($value['dateOrderGroups'])) {
                continue;
            }
            foreach ($value['dateOrderGroups'] as $date_key => $date_value) {
                if (!isset($date_value['date'])) {
                    continue;
                }
                $date = strtotime($date_value['date']);
                foreach ($date_value['currentDateOrders'] as $k => $v) {
                    if (empty($v['fromCity'])) {
                        continue;
                    }
                    $cityId = $v['fromCity']['_id'];

                    $article_bind = [];
                    if (!empty($member_id)) {
                        $article_bind = db("article_binduser")->where('member_id', $member_id)->find();
                    }
                    if (!empty($article_bind['article_id']) && !in_array($article_bind['article_id'], $articleArr)) {
                        $article_id = $article_bind['article_id'];
                    } else {
                        //插入攻略
                        $article_id = $this->getArticle($cityId, $v['orderType'], $articleArr);
                    }

                    if ($article_id > 0) {
                        $articleArr[] = $article_id;
                        $article = db("article")
                            ->alias('a')
                            ->join('attachment t', 'a.thumb=t.id', 'left')
                            ->where("a.id", $article_id)
                            ->field("a.id,a.title,t.filepath")
                            ->find();
                        $res['orders'][$key]['dateOrderGroups'][$date_key]['currentDateOrders'][$k]['article'] = $article;
                    }

                    if ($yesterday <= $date && $date <= $third_day) {
                        if (isset($weather_arr[$cityId])) {//符合日期
                            if (!isset($weather_arr[$cityId]['daily_forecast'][1])) {
                                continue;
                            }

                            //改为明天
                            $res['orders'][$key]['dateOrderGroups'][$date_key]['currentDateOrders'][$k]['fromCity']['weather'] = $weather_arr[$cityId]['daily_forecast'][1];
                        }
                    }
                }
            }
        }

        $shu=[
            'code'=>0,
            'msg'=>'',
            'data'=>$res
        ];


        echo "<pre>";
        var_dump($url);
        var_dump($token);
        var_dump($res);
        echo "</pre>";
        exit;

    }

    //推送定制订单到订单系统
    public function pushCustomOrderDataToOrderSystem($data)
    {
        $kbxToken = new KbxToken();
        $url = $kbxToken->url.'/tripOrder/createOrUpdate';
        $token = 'Bearer ' . $kbxToken->kbxToken();
        $list = json_encode($data);
        trace('推送定制订单数据：'.$list);
        $res = $kbxToken->post_data($url,$list,$token);
        $res = $kbxToken->object_array($res);
        $res = json_decode($res,true);
        if(!is_array($res)){
            $res = [
                'code'=>101,
                'msg'=>$res,
            ];
        }elseif(!isset($res['_id']) || !isset($res['orderNo'])){
            $res['code'] = 101;
        }else{
            $res['code'] = 200;
        }
        return $res;
    }

    //修改定制订单支付状态为已支付
    public function updatePaidCustomOrder($data)
    {
        $kbxToken = new KbxToken();
        $url = $kbxToken->url.'/tripOrder/afterPay';
        $token = 'Bearer ' . $kbxToken->kbxToken();
        $list = json_encode($data);
        $res = $kbxToken->post_data($url,$list,$token);
        $res = $kbxToken->object_array($res);
        return json_decode($res,true) ;
    }

    //小程序 【我的行程】查询客户订单
    public function kbx_custom_order_latest()
    {
        $member_id = $this->member_id;
        $kbxToken = new KbxToken();
        $member = db("member")->where("member_id",$member_id)->field("member_username")->find();
        $user = $kbxToken->kbxUser($member['member_username']);
        if(empty($user['id'])){
            $shu=[
                'code'=>400,
                'msg'=>'找不到user',
            ];
            return json_encode($shu);
        }

        $url = $kbxToken->url.'/corders/latestOrder4User/'.$user['id'];
        $token = 'Bearer ' . $kbxToken->kbxToken();
        $res = $kbxToken->get_data($url, $token);
//        var_dump(json_encode($res));exit;
        $res = $kbxToken->object_array($res);
        //插入当日明日的天气状况
        $today = time();//当天时间戳
        $yesterday = $today-86400;//昨天时间戳
        $third_day = $today+86400+86400;//后天时间戳

        $weather_date = cache('Weather');
        $weather_arr = array();
        foreach ($weather_date as $item) {
            if(isset($item['kbx_id']) && $item['kbx_id']!==''){
                $weather_arr[$item['kbx_id']] = $item;
            }
        }

        $articleArr = array();//存放已推送的文章id
        $shu=[
            'code'=>0,
            'msg'=>'获取成功',
            'data'=>[]
        ];
        $value = $res['order']??[];//由列表变成对象
//        foreach ($res['orders'] as $key=>$value) {
            if (empty($value['dateOrderGroups'])) {
                return json_encode($shu);
            }
            //订单标题
            $value['name'] = $value['name']??"";
            if(!empty($value['servant'])){
                $value['servant']['wxqrcodeAbroad'] = $value['servant']['wxqrcodeAbroad']??(new SDModel())->checkImgUrl('/icon/kbx_service_housekeeper_xiaobei.jpg');
                $value['servant']['wxqrcodeInternal'] = $value['servant']['wxqrcodeInternal']??(new SDModel())->checkImgUrl('/icon/kbx_service_housekeeper_xiaomei.jpg');
            }
            foreach ($value['dateOrderGroups'] as $date_key => $date_value) {
                if (!isset($date_value['date'])) {
                    return json_encode($shu);
                }
                $date = strtotime($date_value['date']);
                foreach ($date_value['currentDateOrders'] as $k => $v) {
                    if (empty($v['fromCity'])) {
                        return json_encode($shu);
                    }
                    $cityId = $v['fromCity']['_id'];

                    $article_bind = [];
                    if (!empty($member_id)) {
                        $article_bind = db("article_binduser")->where('member_id', $member_id)->find();
                    }
                    if (!empty($article_bind['article_id']) && !in_array($article_bind['article_id'], $articleArr)) {
                        $article_id = $article_bind['article_id'];
                    } else {
                        //插入攻略
                        $article_id = $this->getArticle($cityId, $v['orderType'], $articleArr);
                    }

                    if ($article_id > 0) {
                        $articleArr[] = $article_id;
                        $article = db("article")
                            ->alias('a')
                            ->join('attachment t', 'a.thumb=t.id', 'left')
                            ->where("a.id", $article_id)
                            ->field("a.id,a.title,t.filepath")
                            ->find();
                        $value['dateOrderGroups'][$date_key]['currentDateOrders'][$k]['article'] = $article;
                    }

                    if ($yesterday <= $date && $date <= $third_day) {
                        if (isset($weather_arr[$cityId])) {//符合日期
                            if (!isset($weather_arr[$cityId]['daily_forecast'][1])) {
                                return json_encode($shu);
                            }

                            //改为明天
                            $value['dateOrderGroups'][$date_key]['currentDateOrders'][$k]['fromCity']['weather'] = $weather_arr[$cityId]['daily_forecast'][1];

//                            foreach ($weather_arr[$cityId]['daily_forecast'] as $w_value) {
//                                if ($date_value['date'] == $w_value['date']) {
//                                    $res['orders'][$key]['dateOrderGroups'][$date_key]['currentDateOrders'][$k]['fromCity']['weather'] = $w_value;
//                                }
//                            }
                        }
                    }
                }
            }
//        }

        $shu['data']=$value;

        return json_encode($shu);
    }
    //获取订单信息
    public function getOrderDetailByOrderIdFromOrderSystem($data)
    {
        $kbxToken = new KbxToken();
        //从订单系统获取订单信息
        $url = $kbxToken->url.'/corders/getOrder4User';
        $token = 'Bearer ' . $kbxToken->kbxToken();

        $data = json_encode($data);
        log::write('########'.$data);
        //var_dump($token,$data);exit;
        $res = $kbxToken->post_data($url , $data , $token);
        $res = $kbxToken->object_array($res);
        $res = json_decode($res,true);
        return $res;
    }
    //获取用户信息
    public function checkAdminInfo($member_id)
    {
        $kbxToken = new KbxToken();
        if(empty($member_id)){
            $userid = "";
            $isAdmin = false;
        }else{
            $member = db("member")->where("member_id",$member_id)->field("member_username,is_admin")->find();
            $user = $kbxToken->kbxUser($member['member_username']);
            if(empty($user['id'])){
                $shu=[
                    'code'=>400,
                    'msg'=>'找不到user',
                ];
                return json_encode($shu);
            }
            $userid = $user['id'];
            $isAdmin = $member['is_admin']==1?true:false;
        }

        return [$userid,$isAdmin];
    }
    //根据订单号查询用户的出行信息 服务号接口无签名
    public function getOrderDetailByOrderIdWithWx()
    {
        $post = request()->post();
        $member_id = $post['member_id'];
        $memberInfo = $this->checkAdminInfo($member_id);
        if(!is_array($memberInfo)) return $memberInfo;
        list($userid,$isAdmin) = $memberInfo;

        $orderId = $post['order_id']??'';
        $orderNo = $post['order_no']??'';
        if(empty($orderId) && empty($orderNo)) return json_encode(['code'=>101,'msg'=>'缺少订单号！']);
        $data = [
            'id'=>$orderId,
            'orderId'=>$orderNo,
            'userId'=>$userid,
            'isAdmin'=>$isAdmin
        ];
        $res = $this->getOrderDetailByOrderIdFromOrderSystem($data);
        if(!empty($res['msg'])){
            return json_encode(['code'=>101,'msg'=>'订单信息不存在','data'=>[]]);
        }
        //插入当日明日的天气状况
        $today = time();//当天时间戳
        $yesterday = $today-86400;//昨天时间戳
        $third_day = $today+86400+86400;//后天时间戳

        $weather_date = cache('Weather');
        $weather_arr = array();
        foreach ($weather_date as $item) {
            if(isset($item['kbx_id']) && $item['kbx_id']!==''){
                $weather_arr[$item['kbx_id']] = $item;
            }
        }

        $articleArr = array();//存放已推送的文章id
        $shu=[
            'code'=>0,
            'msg'=>'获取成功',
            'data'=>[]
        ];
        $value = $res['order']??[];//由列表变成对象
        if (empty($value['dateOrderGroups'])) {
            return json_encode($shu);
        }

        //订单标题
        $value['name'] = $value['name']??"";
        if(!empty($value['servant'])){
            $value['servant']['wxqrcodeAbroad'] = $value['servant']['wxqrcodeAbroad']??(new SDModel())->checkImgUrl('/icon/kbx_service_housekeeper_xiaobei.jpg');
            $value['servant']['wxqrcodeInternal'] = $value['servant']['wxqrcodeInternal']??(new SDModel())->checkImgUrl('/icon/kbx_service_housekeeper_xiaomei.jpg');
        }
        foreach ($value['dateOrderGroups'] as $date_key => $date_value) {
            if (!isset($date_value['date'])) {
                return json_encode($shu);
            }
            $date = strtotime($date_value['date']);
            foreach ($date_value['currentDateOrders'] as $k => $v) {
                if (empty($v['fromCity'])) {
                    return json_encode($shu);
                }
                $cityId = $v['fromCity']['_id'];

                $article_bind = [];
                if (!empty($member_id)) {
                    $article_bind = db("article_binduser")->where('member_id', $member_id)->find();
                }
                if (!empty($article_bind['article_id']) && !in_array($article_bind['article_id'], $articleArr)) {
                    $article_id = $article_bind['article_id'];
                } else {
                    //插入攻略
                    $article_id = $this->getArticle($cityId, $v['orderType'], $articleArr);
                }

                if ($article_id > 0) {
                    $articleArr[] = $article_id;
                    $article = db("article")
                        ->alias('a')
                        ->join('attachment t', 'a.thumb=t.id', 'left')
                        ->where("a.id", $article_id)
                        ->field("a.id,a.title,t.filepath")
                        ->find();
                    $value['dateOrderGroups'][$date_key]['currentDateOrders'][$k]['article'] = $article;
                }
                if ($yesterday <= $date && $date <= $third_day) {
                    if (isset($weather_arr[$cityId])) {//符合日期
                        if (!isset($weather_arr[$cityId]['daily_forecast'][1])) {
                            return json_encode($shu);
                        }
                        //改为明天
                        $value['dateOrderGroups'][$date_key]['currentDat eOrders'][$k]['fromCity']['weather'] = $weather_arr[$cityId]['daily_forecast'][1];
                    }
                }
                //补充产品提醒信息
                $viatorCode = '';
                if(!empty($v['supplier']['channel']) && $v['supplier']['channel']=='viatorAPI'){
                    $viatorCode = $v['product']['codeBySupplier']??"";
                }
                $productId = $v['product']['productId']??"";
                $notice = [];
                if(!empty($viatorCode)){
                    $viatorGoods = db('goods')->field('goods_id')->where(['code'=>$viatorCode])->find();
                    $notice = db('goods_notice')
                        ->where('goods_id',$viatorGoods['goods_id'])
                        ->find();
                    $notice = $this->formatProductNotice($notice);
                    $notice['source'] = 'viator';
                }elseif(!empty($productId)){
                    $notice = db('product_notice')
                        ->where('product_id',$productId)
                        ->find();
                    $notice = $this->formatProductNotice($notice);
                    $notice['source'] = 'self';
                }
                $value['dateOrderGroups'][$date_key]['currentDateOrders'][$k]['notice'] = $notice;
            }
        }

        $shu['data']=$value;
        return json_encode($shu);
    }

    //格式化提醒信息
    public function formatProductNotice($data)
    {
        if(empty($data)) return [];
        unset($data['pick_up_address_json'],$data['assemble_address_json'],$data['assemble_address_img']);
//        $data['pick_up_address_json'] = empty($data['pick_up_address_json'])?[]:
//            json_decode($data['pick_up_address_json'],true);
//        $data['assemble_address_json'] = empty($data['assemble_address_json'])?[]:
//            json_decode($data['assemble_address_json'],true);
//        $data['assemble_address_img'] = empty($data['assemble_address_img'])?[]:
//            explode(',',$data['assemble_address_img']);
        $data['exchange_ticket_img'] = empty($data['exchange_ticket_img'])?[]:
            explode(',',$data['exchange_ticket_img']);

        return $data;
    }
    //根据订单号查询用户的出行信息 小程序接口走签名
    public function getOrderDetailByOrderId()
    {
        $member_id = $this->member_id;
        $post = request()->post();
        $memberInfo = $this->checkAdminInfo($member_id);
        if(!is_array($memberInfo)) return $memberInfo;
        list($userid,$isAdmin) = $memberInfo;

        $orderId = $post['order_id']??'';
        $orderNo = $post['order_no']??'';
        if(empty($orderId) && empty($orderNo)) return json_encode(['code'=>101,'msg'=>'缺少订单号！']);
        $data = [
            'id'=>$orderId,
            'orderId'=>$orderNo,
            'userId'=>$userid,
            'isAdmin'=>$isAdmin
        ];
        $res = $this->getOrderDetailByOrderIdFromOrderSystem($data);
//        var_dump($res['msg']);
        if(!empty($res['msg'])){
            return json_encode(['code'=>101,'msg'=>'订单信息不存在','data'=>[]]);
        }
        //插入当日明日的天气状况
        $today = time();//当天时间戳
        $yesterday = $today-86400;//昨天时间戳
        $third_day = $today+86400+86400;//后天时间戳

        $weather_date = cache('Weather');
        $weather_arr = array();
        foreach ($weather_date as $item) {
            if(isset($item['kbx_id']) && $item['kbx_id']!==''){
                $weather_arr[$item['kbx_id']] = $item;
            }
        }

        $articleArr = array();//存放已推送的文章id
        $shu=[
            'code'=>0,
            'msg'=>'获取成功',
            'data'=>[]
        ];
        $value = $res['order']??[];//由列表变成对象
        if (empty($value['dateOrderGroups'])) {
            return json_encode($shu);
        }
        //订单标题
        $value['name'] = $value['name']??"";
        if(!empty($value['servant'])){
            $value['servant']['wxqrcodeAbroad'] = $value['servant']['wxqrcodeAbroad']??(new SDModel())->checkImgUrl('/icon/kbx_service_housekeeper_xiaobei.jpg');
            $value['servant']['wxqrcodeInternal'] = $value['servant']['wxqrcodeInternal']??(new SDModel())->checkImgUrl('/icon/kbx_service_housekeeper_xiaomei.jpg');
        }
        foreach ($value['dateOrderGroups'] as $date_key => $date_value) {
            if (!isset($date_value['date'])) {
                return json_encode($shu);
            }
            $date = strtotime($date_value['date']);
            foreach ($date_value['currentDateOrders'] as $k => $v) {
                if (empty($v['fromCity'])) {
                    return json_encode($shu);
                }
                $cityId = $v['fromCity']['_id'];

                $article_bind = [];
                if (!empty($member_id)) {
                    $article_bind = db("article_binduser")->where('member_id', $member_id)->find();
                }
                if (!empty($article_bind['article_id']) && !in_array($article_bind['article_id'], $articleArr)) {
                    $article_id = $article_bind['article_id'];
                } else {
                    //插入攻略
                    $article_id = $this->getArticle($cityId, $v['orderType'], $articleArr);
                }

                if ($article_id > 0) {
                    $articleArr[] = $article_id;
                    $article = db("article")
                        ->alias('a')
                        ->join('attachment t', 'a.thumb=t.id', 'left')
                        ->where("a.id", $article_id)
                        ->field("a.id,a.title,t.filepath")
                        ->find();
                    $value['dateOrderGroups'][$date_key]['currentDateOrders'][$k]['article'] = $article;
                }
                if ($yesterday <= $date && $date <= $third_day) {
                    if (isset($weather_arr[$cityId])) {//符合日期
                        if (!isset($weather_arr[$cityId]['daily_forecast'][1])) {
                            return json_encode($shu);
                        }
                        //改为明天
                        $value['dateOrderGroups'][$date_key]['currentDat eOrders'][$k]['fromCity']['weather'] = $weather_arr[$cityId]['daily_forecast'][1];
                    }
                }
            }
        }
        $shu['data']=$value;
        return json_encode($shu);
    }

    //刷新userToken
    public function refreshUserToken()
    {
        $oldUserToken = input('user_token');
        $member = db("member")->where('token',$oldUserToken)->find();
        if(empty($oldUserToken) || empty($member)){
            //代表用户未登录，需要重新登陆
            $data = [
                'code'=>-102,
                'msg'=>'用户token有误！ 授权失败'
            ];
            return json_encode($data);
        }
        if($member['token_time'] < time()){//新刷取token
            $newUserToken = $this->updateUserToken($member['member_id']);
            if(empty($newUserToken)){
                $data = [
                    'code'=>-101,
                    'msg'=>'获取userToken失败！ 授权失败'
                ];
                return json_encode($data);
            }
        }else{
            $newUserToken = $oldUserToken;
        }
        $data = [
            'code'=>200,
            'msg'=>'刷新成功，授权成功',
            'data'=>[
                'userToken'=>$newUserToken
            ]
        ];
        return json_encode($data);
    }
    
    //获取拼游订单列表
    public function getGrouptoursOrderList($member_kbx_id)
    {
        $kbxToken = new KbxToken();
        //从订单系统获取订单信息
        $url = $kbxToken->url.'/client/users/'.$member_kbx_id.'/carPoolOrders';
        $token = 'Bearer ' . $kbxToken->kbxToken();
        $res = $kbxToken->get_data($url , $token);
        $res = $kbxToken->object_array($res);
        if(!empty($res['msg'])){
            trace('用户'.$member_kbx_id.'获取订单列表失败');
            trace('返回信息'.json_encode($res));
            return "";
        }
        return $res;
    }

    //获取拼游订单详情
    public function getGrouptoursOrderInfo($member_kbx_id,$order_no)
    {
        $kbxToken = new KbxToken();
        $url = $kbxToken->url.'/client/users/'.$member_kbx_id.'/getOrderDetailByOrderNo/'.$order_no;
        $token = 'Bearer ' . $kbxToken->kbxToken();
        $res = $kbxToken->get_data($url, $token);
        $res = $kbxToken->object_array($res);
        return $res;
    }

    //获取拼游团详情
    public function getGrouptoursGroupInfo($order_id,$userKbxId='')
    {
        $kbxToken = new KbxToken();
        //从订单系统获取订单信息
        $url = $kbxToken->url.'/carpool/order/'.$order_id;
        if(!empty($userKbxId)) $url .= '?user='.$userKbxId;
        $token = 'Bearer ' . $kbxToken->kbxToken();
        $res = $kbxToken->get_data($url , $token);
        $res = $kbxToken->object_array($res);
        if(!empty($res['msg'])){
            trace('拼团订单'.$order_id.'获取失败');
            trace('返回信息'.json_encode($res));
        }
        return $res;
    }

    //通过订单系统订单状态和支付状态获取定制接口的订单状态
    public function getStatusByOrderStatus($orderStatus,$paymentStatus)
    {
        $Status = 1;//待付款
        if($orderStatus=='pending' || $orderStatus=='carpool' || $orderStatus=='notpay'){
            if($paymentStatus=='pending'){
                $Status = 1;//待付款
            }elseif($paymentStatus=='paid'){
                $Status = 2;//已付款待使用
            }elseif($paymentStatus=='refunding'){
                $Status = 5;//退款申请中
            }elseif($paymentStatus=='rejected'){
                $Status = 9;//拒绝退款
            }
        }elseif($orderStatus=='toBeStarting'){
            if($paymentStatus=='paid'){
                $Status = 2;//已付款待使用
            }elseif($paymentStatus=='refunding'){
                $Status = 5;//退款申请中
            }elseif($paymentStatus=='rejected'){
                $Status = 9;//拒绝退款
            }
        }elseif($orderStatus=='reviewed'){//已评价
            $Status = 4;
        }elseif($orderStatus=='finished'){//已使用待评价
            $Status = 3;
        }elseif($orderStatus=='canceled'){//已取消
            $Status = 6;
        }elseif($orderStatus=='expired'){//已过期
            $Status = 7;
        }elseif($orderStatus=='unknown'){//下单失败
            $Status = 10;
        }

        return $Status;
    }

    //发送通知到微信群
    public function sendNewProductounding($data)
    {
        $kbxToken = new KbxToken();
        //从订单系统获取订单信息
        $url = $kbxToken->url.'/wwRobot/newProduct';
        $token = 'Bearer ' . $kbxToken->kbxToken();
        $list = json_encode($data);
        $res = $kbxToken->post_data($url,$list,$token);
        //记录日志
        trace('产品商家上架通知');
        trace('通知内容：'.$list);
        trace('结果：'.$res);
        $res = $kbxToken->object_array($res);
        return $res;
    }

    //发送OTA事项提醒
    public function addOTANoticeItem($data)
    {
        $kbxToken = new KbxToken();
        //从订单系统获取订单信息
        $url = $kbxToken->url.'/workItem4Product/new';
        $token = 'Bearer ' . $kbxToken->kbxToken();
        $list = json_encode($data);
        $res = $kbxToken->post_data($url,$list,$token);
        //记录日志
        trace('创建OTA提醒事项通知');
        trace('通知内容：'.$list);
        trace('结果：'.$res);
        $res = $kbxToken->object_array($res);
        return $res;
    }

    //操作员增加积分信息
    public function addAdminScore($source,$source_id,$record,$admin_id=0)
    {
        //如果没有管理员 默认是操作员
        $admin_id = $admin_id > 0 ? $admin_id : Cookie::get('admin');
        //根据不同类型增加不同的分数
        $_source = [
            'dev'=>1,
            'POI'=>2,
            'product'=>3,
            'driverComment'=>1,
        ];

        $data = [
            'admin'=>$admin_id,
            'record'=>$record,
            'source'=>$source,
            'score'=>$_source[$source],
        ];
        $res = $this->pushAddAdminScore($data);
        //添加成功 记录日志
        db('admin_score_log')->insert([
            'admin_id'=>$admin_id,
            'source'=>$source,
            'source_id'=>$source_id,
            'score'=>$_source[$source],
            'desc'=>$record,
            'create_time'=>time(),
        ]);
        return $res;
    }

    //操作员增加积分信息推送到订单系统
    public function pushAddAdminScore($data)
    {
        $kbxToken = new KbxToken();
        //从订单系统获取订单信息
        $url = $kbxToken->url.'/admin/addScorebyMySqlId';
        $token = 'Bearer ' . $kbxToken->kbxToken();
        $list = json_encode($data);
        $res = $kbxToken->post_data($url,$list,$token);
        //记录日志
        trace('操作员增加积分信息');
        trace('请求参数：'.$list);
        trace('结果：'.$res);
        $res = $kbxToken->object_array($res);
        return $res;
    }
    //同步国家信息
    public function syncNewCountry($post)
    {
        //必须包含name nameen code currency abbreviation
        if(empty($post['name']) || empty($post['eng_name']) || empty($post['code']) || empty($post['currency_code']) || empty($post['abbreviation'])){
            trace('国家同步失败,缺少关键参数');
            return false;
        }
//        $country['kbx_id'] = '5e99153a11a5c0decbef9402';//模拟数据
        $post_data = [
            'country'=>[
                'name'=>$post['name'],
                'nameen'=>$post['eng_name'],
                'code'=>$post['code'],
                'show4Driver'=>true,
                'showIn2C'=>true,
                'showIn2B'=>true,
                'abbreviation'=>$post['abbreviation'],
                'currency'=>$post['currency_code'],
                'initial'=>strtolower($post['eng_name'][0]),//首字母小写
                'level'=>1,
            ]
        ];

        return $post_data;
    }
    //同步城市信息
    public function syncNewCity($post)
    {
        //必须包含name nameen country
        if(empty($post['name']) || empty($post['eng_name']) || empty($post['groupid'])){
            trace('城市同步失败,缺少关键参数');
            return false;
        }
        $country = db('city')->field('kbx_id')->find($post['groupid']);
        if(empty($country['kbx_id'])){
            trace('城市同步失败,国家信息暂未同步');
            return false;
        }
//        $country['kbx_id'] = '5e99153a11a5c0decbef9402';//模拟数据
        $post_data = [
          'city'=>[
              'name'=>$post['name'],
              'nameen'=>$post['eng_name'],
              'country'=>$country['kbx_id'],
              'show4Driver'=>false,
              'showIn2C'=>false,
              'showIn2B'=>false,
              'lat'=>$post['lat'],
              'lng'=>$post['lng'],
          ]
        ];

        return $post_data;
    }

    public function pushNewCountryToKbx($data)
    {
        //检验数据
        $data = $this->syncNewCountry($data);
        if(empty($data)){
            return false;
        }
        $kbxToken = new KbxToken();
        //从订单系统获取订单信息
        $url = $kbxToken->url.'/countries/newCountryBySystem';
        $token = 'Bearer ' . $kbxToken->kbxToken();
        $list = json_encode($data);
        $res = $kbxToken->post_data($url,$list,$token);
        //记录日志
        trace('国家同步信息');
        trace('请求参数：'.$list);
        trace('结果：'.$res);
        $res = $kbxToken->object_array(json_decode($res));
        return $res;
    }

    public function pushNewCityToKbx($data)
    {
        //检验数据
        $data = $this->syncNewCity($data);
        if(empty($data)){
            return false;
        }
        $kbxToken = new KbxToken();
        //从订单系统获取订单信息
        $url = $kbxToken->url.'/cities/newCityBySystem';
        $token = 'Bearer ' . $kbxToken->kbxToken();
        $list = json_encode($data);
        $res = $kbxToken->post_data($url,$list,$token);
        //记录日志
        trace('城市同步信息');
        trace('请求参数：'.$list);
        trace('结果：'.$res);
        $res = $kbxToken->object_array(json_decode($res));
        return $res;
    }

    //定制系统已绑定KBX_ID的国家的数据同步
    public function syncCountryDataBySystem()
    {
        //获取国家列表信息
        $kbxToken = new KbxToken();
        //从订单系统获取订单信息
        $url = $kbxToken->url.'/countries/listCountries';
        $token = 'Bearer ' . $kbxToken->kbxToken();
        $res = $kbxToken->get_data($url , $token);
        $res = $kbxToken->object_array($res);
        if(!empty($res['msg'])){
            trace('获取国家列表失败');
            trace('返回信息'.json_encode($res));
            echo 'fail';exit;
        }
        //获取已匹配的国家列表
        $countryList = db('city')->where(['kbx_id'=>['neq',''],'type'=>'COUNTRY'])->field('id,name,code,abbreviation,kbx_id')->select();
        trace('共'.count($countryList).'条数据');
        db::startTrans();
        try{
            foreach ($countryList as $c_k=>$country){
                foreach ($res as $key=>$value){
                    if($value['id']==$country['kbx_id'] && empty($country['code']) && empty($country['abbreviation'])){
                        //更新数据
                        $updData = [];
                        $updData['code'] = $value['code'];
                        $updData['abbreviation'] = $value['abbreviation'];
                        db('city')->where(['id'=>$country['id']])->update($updData);
                        trace('第'.$c_k.'条：同步'.$country['name'].'成功!');
                        unset($res[$key]);//删除已同步的数据
                        break;
                    }
                }
            }
            db::commit();
            echo 'success';
        }catch (Exception $e){
            db::rollback();
            echo $e->getMessage();
        }
    }

    //缺少经纬的城市通过谷歌接口获取 gid lat lng address
    public function addLatAndLngToCity()
    {
        ignore_user_abort();//关闭浏览器仍然运行
        set_time_limit(0);//程序运行不停止
        //1获取需要补录的城市数据
        $list = db('city')->where(['type'=>'CITY','kbx_id'=>['eq',''],'lat'=>['eq',''],'lng'=>['eq','']])->field('id,name,eng_name')->select();
        trace('共'.count($list).'条数据');
        //2调用谷歌地图接口获取经纬度和gid address 信息 获取失败则跳过
        db::startTrans();
        try{
            foreach ($list as $key=>$value){
                $result = (new GoogleMap())->getAddressInfo($value['name']);
                $result = json_decode($result,true);
                if(empty($result['candidates']) || empty($result['status']) || $result['status']!='OK'){
                    $result = (new GoogleMap())->getAddressInfo($value['eng_name']);
                    $result = json_decode($result,true);
                    if(empty($result['candidates']) || empty($result['status']) || $result['status']!='OK'){
                        continue;
                    }
                }
                $updData = [];
                $updData['gid'] = $result['candidates'][0]['place_id']??'';
                $updData['lat'] = $result['candidates'][0]['geometry']['location']['lat']??'';
                $updData['lng'] = $result['candidates'][0]['geometry']['location']['lng']??'';
                $updData['address'] = $result['candidates'][0]['formatted_address']??'';
                db('city')->where(['id'=>$value['id']])->update($updData);
                trace('第'.$key.'条:'.$value['name'].'更新成功！');
            }

            db::commit();
            echo "success";
        }catch (Exception $e){
            db::rollback();
            echo $e->getMessage();
        }
    }

    //同步未绑定kbx_id的城市到订单系统
    public function syncNoKbxIdCityToKbxSystem(){
        ignore_user_abort();//关闭浏览器仍然运行
        set_time_limit(0);//程序运行不停止
        //1获取需要补录的城市数据
        $citylist = db('city c')->join('city country','country.id=c.groupid','left')
            ->where(['c.type'=>'CITY','c.kbx_id'=>['eq',''],'c.lat'=>['neq',''],'c.lng'=>['neq',''],'c.deleted'=>['eq',0]])
            ->field('c.id,c.name,c.eng_name,c.groupid,c.lat,c.lng,c.gid,c.address,country.kbx_id')
            ->select();
        trace('共'.count($citylist).'条数据');
        //2调用谷歌地图接口获取经纬度和gid address 信息 获取失败则跳过
        $kbxToken = new KbxToken();
        //从订单系统获取订单信息
        $url = $kbxToken->url.'/cities/newCityBySystem';
        $token = 'Bearer ' . $kbxToken->kbxToken();
        db::startTrans();
        try{
            foreach ($citylist as $key=>$value){
                //缺少数据直接跳过
                if(empty($value['kbx_id']) || empty($value['name']) || empty($value['eng_name'])
                    || empty($value['lat']) || empty($value['lng']) ){
                    continue;
                }
                $post_data = [
                    'city'=>[
                        'name'=>$value['name'],
                        'nameen'=>$value['eng_name'],
                        'country'=>$value['kbx_id'],
                        'show4Driver'=>false,
                        'showIn2C'=>false,
                        'showIn2B'=>false,
                        'lat'=>$value['lat'],
                        'lng'=>$value['lng'],
                        'gid'=>$value['gid']??'',
                        'address'=>$value['address']??'',
                    ]
                ];
                $list = json_encode($post_data);
                $res = $kbxToken->post_data($url,$list,$token);
                $res = $kbxToken->object_array(json_decode($res));
                if(!empty($res['id'])){
                    db('city')->where(['id'=>$value['id']])->update(['kbx_id'=>$res['id']]);
                    trace('第'.$key.'条：'.$value['name'].'同步成功');
                }else{
                    continue;
                }
            }

            db::commit();
            echo "success";
        }catch (Exception $e){
            db::rollback();
            echo $e->getMessage();
        }

    }

    //供应商下架产品通知采购商下架
    public function pullOffShelvesNotifyToKbx($standard_id)
    {
        if(empty($standard_id)) return false;
        $kbxToken = new KbxToken();
        //从订单系统获取订单信息
        $url = $kbxToken->bSellerBackendUrl.'/miniMallAdmin/pullOffShelvesNotify';
        $token = 'Bearer ' . $kbxToken->kbxToken();
        $list = json_encode(['standardId'=>$standard_id]);
        $res = $kbxToken->post_data($url,$list,$token);
        //记录日志
        trace('供应商下架产品通知采购商下架');
        trace('请求参数：'.$list);
        trace('结果：'.$res);
        $res = $kbxToken->object_array(json_decode($res));
        return $res;
    }

    //供应商上架产品通知采购商上架
    public function putOnSaleNotifyToKbx($standard_id)
    {
        if(empty($standard_id)) return false;
        $kbxToken = new KbxToken();
        //从订单系统获取订单信息
        $url = $kbxToken->bSellerBackendUrl.'/miniMallAdmin/putOnSaleNotify';
        $token = 'Bearer ' . $kbxToken->kbxToken();
        $list = json_encode(['standardId'=>$standard_id]);
        $res = $kbxToken->post_data($url,$list,$token);
        //记录日志
        trace('供应商上架产品后上架通知采购商');
        trace('请求参数：'.$list);
        trace('结果：'.$res);
        $res = $kbxToken->object_array(json_decode($res));
        return $res;
    }


    //修改产品的供应商同步到订单系统
    public function changeSupplierToKBXSystem($standardId,$supplierId)
    {
        $kbxToken = new KbxToken();
        //从订单系统获取订单信息
        $url = $kbxToken->bSellerBackendUrl.'/miniMallAdmin/changeSupplier';
        $token = 'Bearer ' . $kbxToken->kbxToken();
        $list = json_encode(["standardId"=>$standardId,"supplierId"=>$supplierId]);
        $res = $kbxToken->post_data($url,$list,$token);
        //记录日志
        trace('同步产品的供应商信息');
        trace('请求参数：'.$list);
        trace('结果：'.$res);
        $res = $kbxToken->object_array(json_decode($res));
        return $res;
    }

    //产品首次上架通知【20200921 废弃】
    public function postNewToBProductNotify($postdata)
    {
        $kbxToken = new KbxToken();
        //从订单系统获取订单信息
        $url = $kbxToken->url.'/wwRobot/newToBProduct';
        $token = 'Bearer ' . $kbxToken->kbxToken();
        $list = json_encode(['product'=>$postdata]);
        $res = $kbxToken->post_data($url,$list,$token);
        //记录日志
        trace('产品首次上架通知');
        trace('请求参数：'.$list);
        trace('结果：'.$res);
        $res = $kbxToken->object_array(json_decode($res));
        return $res;
    }

    //产品到期通知
    public function preToBSalesExpireDateNotifyV3($postdata)
    {
        $kbxToken = new KbxToken();
        //从订单系统获取订单信息
        $url = $kbxToken->url.'/wwRobot/preToBSalesExpireDateNotifyV3';
        $token = 'Bearer ' . $kbxToken->kbxToken();
        $list = json_encode(['products'=>$postdata]);
        $res = $kbxToken->post_data($url,$list,$token);
        //记录日志
        trace('产品到期预警通知');
        trace('请求参数：'.$list);
        trace('结果：'.$res);
        $res = $kbxToken->object_array(json_decode($res));
        return $res;
    }

    //供应商产品上架通知分销商
    public function putOnSaleNotifyV2ToKbx($postdata)
    {
        if(empty($postdata)) return false;
        $kbxToken = new KbxToken();
        //从订单系统获取订单信息
        $url = $kbxToken->bSellerBackendUrl.'/miniMallAdmin/putOnSaleNotifyV2';
        $token = 'Bearer ' . $kbxToken->kbxToken();
        $list = json_encode(['product'=>$postdata]);
        $res = $kbxToken->post_data($url,$list,$token);
        //记录日志
        trace('供应商产品上架通知分销商');
        trace('请求参数：'.$list);
        trace('结果：'.$res);
        $res = $kbxToken->object_array(json_decode($res));
        if(isset($res['code']) && $res['code']==200){
            return true;
        }else{
            return $res;
        }

    }

    //服务号通知供应商产品下架
    public function sendProductOffAlertNotify($standardInfo)
    {
        if(empty($standardInfo['supplier_admin_id'])) return false;
        $supplierAdminInfo = (new Common())->getSupplierAdminInfo($standardInfo['supplier_admin_id']);
        if(empty($supplierAdminInfo['company_id'])) return false;
        $this->sendProductOffAlert([
            'supplier'=>$supplierAdminInfo['company_id'],
            'product'=>[
                'id'=>$standardInfo['id'],
                'name'=>$standardInfo['name'],
            ],
        ]);
    }

    public function sendProductOffAlert($postdata)
    {
        if(empty($postdata)) return false;
        $kbxToken = new KbxToken();
        //从订单系统获取订单信息
        $url = $kbxToken->bSellerBackendUrl.'/supplier/notify/sendProductOffAlert';
        $token = 'Bearer ' . $kbxToken->kbxToken();
        $list = json_encode($postdata);
        $res = $kbxToken->post_data($url,$list,$token);
        //记录日志
        trace('服务号通知供应商产品下架');
        trace('请求参数：'.$list);
        trace('结果：'.$res);
        $res = $kbxToken->object_array(json_decode($res));
        if(isset($res['code']) && $res['code']==200){
            return true;
        }else{
            return $res;
        }

    }

    //供应商自营的产品直接小程序上架
    public function onSaleWxSoftSupplierStandard($standardId,$supplierId)
    {
        $kbxToken = new KbxToken();
        //从订单系统获取订单信息
        $url = $kbxToken->bSellerBackendUrl.'/miniMallAdmin/putSelfCommodityOnSale';
        $token = 'Bearer ' . $kbxToken->kbxToken();
        $list = json_encode([
            'standardId'=>$standardId,
            'supplierId'=>$supplierId
        ]);
        $res = $kbxToken->post_data($url,$list,$token);
        //记录日志
        trace('供应商自营的产品直接小程序上架');
        trace('请求地址：'.$url);
        trace('结果：'.$res);
        $res = $kbxToken->object_array(json_decode($res));
        if(isset($res['code']) && $res['code']==200){
            return true;
        }else{
            return $res;
        }
    }

    public function onSaleWxSoftSupplierStandardBySupplier(Request $request)
    {
        if($request->isPost()){
            $post = $request->post();
            if(empty($post['standardId'])) return false;
            if(empty($post['supplierId'])) return false;
            return $this->onSaleWxSoftSupplierStandard($post['standardId'],$post['supplierId']);
        }else{
            return false;
        }
    }

    //创建攻略推送到订单系统
    public function createTravelGuideToKbx($guideId,$category,$supplierId)
    {
        $kbxToken = new KbxToken();
        //从订单系统获取订单信息
        $url = $kbxToken->bSellerBackendUrl.'/TravelGuide/createGuide';
        $token = 'Bearer ' . $kbxToken->kbxToken();
        $list = json_encode([
            'guideId'=>$guideId,
            'category'=>$category,
            'supplierId'=>$supplierId
        ]);
        $res = $kbxToken->post_data($url,$list,$token);
        //记录日志
        trace('创建攻略推送到订单系统');
        trace('请求地址：'.$url);
        trace('结果：'.$res);
        $res = $kbxToken->object_array(json_decode($res));
        if(isset($res['code']) && $res['code']==200){
            return true;
        }else{
            return $res;
        }
    }
    //修改攻略推送到订单系统
    public function updateTravelGuideToKbx($guideId,$fromCategory,$toCategory,$supplierId)
    {
        $kbxToken = new KbxToken();
        //从订单系统获取订单信息
        $url = $kbxToken->bSellerBackendUrl.'/TravelGuide/updateGuideCategory';
        $token = 'Bearer ' . $kbxToken->kbxToken();
        $list = json_encode([
            'guideId'=>$guideId,
            'fromCategory'=>$fromCategory,
            'toCategory'=>$toCategory,
            'supplierId'=>$supplierId
        ]);
        $res = $kbxToken->post_data($url,$list,$token);
        //记录日志
        trace('修改攻略推送到订单系统');
        trace('请求地址：'.$url);
        trace('结果：'.$res);
        $res = $kbxToken->object_array(json_decode($res));
        if(isset($res['code']) && $res['code']==200){
            return true;
        }else{
            return $res;
        }
    }
    //删除攻略推送到订单系统
    public function deleteTravelGuideToKbx($guideId,$category,$supplierId)
    {
        $kbxToken = new KbxToken();
        //从订单系统获取订单信息
        $url = $kbxToken->bSellerBackendUrl.'/TravelGuide/removeGuide';
        $token = 'Bearer ' . $kbxToken->kbxToken();
        $list = json_encode([
            'guideId'=>$guideId,
            'category'=>$category,
            'supplierId'=>$supplierId
        ]);
        $res = $kbxToken->post_data($url,$list,$token);
        //记录日志
        trace('删除攻略推送到订单系统');
        trace('请求地址：'.$url);
        trace('结果：'.$res);
        $res = $kbxToken->object_array(json_decode($res));
        if(isset($res['code']) && $res['code']==200){
            return true;
        }else{
            return $res;
        }
    }

    //接口返回
    public function createTravelGuideToKbxBySupplier($guideId,$category,$supplierId)
    {
        $res = $this->createTravelGuideToKbx($guideId,$category,$supplierId);
        if(is_array($res)){
            return $this->result('error',$res,-400,'json');
        }else{
            return $this->result('success',[],200,'json');

        }
    }
    public function updateTravelGuideToKbxBySupplier($guideId,$fromCategory,$toCategory,$supplierId)
    {
        $res = $this->updateTravelGuideToKbx($guideId,$fromCategory,$toCategory,$supplierId);
        if(is_array($res)){
            return $this->result('error',$res,-400,'json');
        }else{
            return $this->result('success',[],200,'json');

        }
    }
    public function deleteTravelGuideToKbxBySupplier($guideId,$category,$supplierId)
    {
        $res = $this->deleteTravelGuideToKbx($guideId,$category,$supplierId);
        if(is_array($res)){
            return $this->result('error',$res,-400,'json');
        }else{
            return $this->result('success',[],200,'json');

        }
    }

    //检索expedia景点或酒店
    public function findRegionsAndPropertiesByName($keywords){
        $kbxToken = new KbxToken();
        //从订单系统获取订单信息
        $url = $kbxToken->bSellerBackendUrl.'/expedia/findRegionsAndPropertiesByName/'.urlencode($keywords);
        $token = 'Bearer ' . $kbxToken->kbxToken();
        $res = $kbxToken->get_data($url,$token);
        //记录日志
        trace('检索expedia景点或酒店列表');
        trace('请求地址：'.$url);
        return $res;
    }

    //基于regionId搜索酒店
    public function searchHotelsByRegion($data=[]){
        if(empty($data)) return false;
        $required = ['regionId','checkIn','checkOut','occupancy'];
        foreach ($required as $key=>$value){
            if(!array_key_exists($value,$data)) return false;
        }
        $filter = empty($data['filter'])?[
            "ratingMax"=> 5,
            "ratingMin"=>0,
            "ratingGuestMin"=>0,
            "ratingGuestMax"=>5,
            "categories"=>[],
            "themes"=>[],
            "combinedAmenities"=>[]
        ]:$data['filter'];
        $sortBy['key'] = empty($data['sortBy'])?'score':$data['sortBy'];
        $page = empty($data['page'])?1:$data['page'];
        $offset = empty($data['offset'])?100:$data['offset'];
        $lang = empty($data['lang'])?'zh':$data['lang'];
        $kbxToken = new KbxToken();
        //从订单系统获取订单信息
        $url = $kbxToken->bSellerBackendUrl.'/expedia/searchHotelsByRegion2/'.$data['regionId'];
        $token = 'Bearer ' . $kbxToken->kbxToken();
        $postData = [
            'filter'=>$filter,
            'params'=>[
                'checkin'=>$data['checkIn'],
                'checkout'=>$data['checkOut'],
                'occupancy'=>$data['occupancy'],
            ],
            'sortBy'=>$sortBy,
            'page'=>$page,
            'offset'=>$offset,
            'lang'=>$lang
        ];
        if(!empty($data['price_range'])) $postData['price_range'] = $data['price_range'];
        if(!empty($data['star_level'])) $postData['star_level'] = $data['star_level'];
        $list = json_encode($postData);
        $res = $kbxToken->post_data($url,$list,$token);
        //记录日志
        trace('检索expedia景点或酒店列表');
        trace('请求地址：'.$url);
        return json_decode($res,true);
    }
    //基于propertyId搜索相似的酒店
    public function searchHotelsByProperty($propertyId,$checkIn,$checkOut,$occupancy){
        $kbxToken = new KbxToken();
        //从订单系统获取订单信息
        $url = $kbxToken->bSellerBackendUrl.'/expedia/searchHotelsByProperty/'.$propertyId;
        $token = 'Bearer ' . $kbxToken->kbxToken();
        $list = json_encode([
            'checkin'=>$checkIn,
            'checkout'=>$checkOut,
            'occupancy'=>$occupancy
        ]);
        $res = $kbxToken->post_data($url,$list,$token);
        //记录日志
        trace('检索expedia景点或酒店列表');
        trace('请求地址：'.$url);
        return $res;
    }

    //基于$propertyId查询酒店详情和酒店房间信息
    public function getHotelDetails($data){
        if(empty($data)) return false;
        $required = ['propertyId','checkIn','checkOut','occupancy'];
        foreach ($required as $key=>$value){
            if(!array_key_exists($value,$data)) return false;
        }
        $kbxToken = new KbxToken();
        //从订单系统获取订单信息
        $url = $kbxToken->bSellerBackendUrl.'/expedia/getHotelDetails/'.$data['propertyId'];
        $token = 'Bearer ' . $kbxToken->kbxToken();
        $list = json_encode([
            'checkin'=>$data['checkIn'],
            'checkout'=>$data['checkOut'],
            'occupancy'=>$data['occupancy']
        ]);
        $res = $kbxToken->post_data($url,$list,$token);
        //记录日志
        trace('获取Expedia酒店的详情和房间');
        trace('请求地址：'.$url);
        return json_decode($res,true);
    }

    ###############################Expedia 国家 城市 POI 数据##################3
    public function listEContinents()
    {
        $kbxToken = new KbxToken();
        //从订单系统获取订单信息
        $url = $kbxToken->bSellerBackendUrl.'/expedia/listEContinents';
        $token = 'Bearer ' . $kbxToken->kbxToken();
        $res = $kbxToken->get_data($url,$token);
        //记录日志
        trace('获取订单系统缓存的expedia大洲');
        trace('请求地址：'.$url);
        return $res;
    }

    public function listECountrys($eId='')
    {
        if(empty($eId)) return [];
        $kbxToken = new KbxToken();
        //从订单系统获取订单信息
        $url = $kbxToken->bSellerBackendUrl.'/expedia/listECountrys?eId='.$eId;
        $token = 'Bearer ' . $kbxToken->kbxToken();
        $res = $kbxToken->get_data($url,$token);
        //记录日志
        trace('获取订单系统缓存的expedia国家');
        trace('请求地址：'.$url);
        return $res;
    }

    public function getAllECountries()
    {
        $kbxToken = new KbxToken();
        //从订单系统获取订单信息
        $url = $kbxToken->bSellerBackendUrl.'/expedia/getAllECountries';
        $token = 'Bearer ' . $kbxToken->kbxToken();
        $res = $kbxToken->get_data($url,$token);
        //记录日志
        trace('获取订单系统缓存的expedia国家');
        trace('请求地址：'.$url);
        return $res;
    }

    public function listCityByCountry($eId='',$page=1,$limit=50)
    {
        if(empty($eId)) return [];
        $kbxToken = new KbxToken();
        //从订单系统获取订单信息
        $url = $kbxToken->bSellerBackendUrl.'/expedia/listCityByCountry?eId='.$eId.'&page='.$page.'&limit='.$limit;
        $token = 'Bearer ' . $kbxToken->kbxToken();
        $res = $kbxToken->get_data($url,$token);
        //记录日志
        trace('获取订单系统缓存的expedia城市');
        trace('请求地址：'.$url);
        return $res;
    }

    public function listERegionByParentEId($eId='')
    {
        if(empty($eId)) return [];
        $kbxToken = new KbxToken();
        //从订单系统获取订单信息
        $url = $kbxToken->bSellerBackendUrl.'/expedia/listERegionByParentEId?eId='.$eId;
        $token = 'Bearer ' . $kbxToken->kbxToken();
        $res = $kbxToken->get_data($url,$token);
        //记录日志
        trace('获取订单系统缓存的expedia城市下的地区的POI列表');
        trace('请求地址：'.$url);
        return $res;
    }

    public function listERegionByEIds($eIds=[])
    {
        if(empty($eIds)) return [];
        $kbxToken = new KbxToken();
        //从订单系统获取订单信息
        $url = $kbxToken->bSellerBackendUrl.'/expedia/listERegionByEIds';
        $token = 'Bearer ' . $kbxToken->kbxToken();
        //数据去重
        $list = json_encode([
            'eIds'=>array_values(array_unique($eIds))
        ]);
        $res = $kbxToken->post_data($url,$list,$token);
        //记录日志
        trace('获取订单系统缓存的expedia的POI列表');
        trace('请求地址：'.$url);
        return json_decode($res,true);
    }

    public function getERegionByEId($eId='')
    {
        if(empty($eId)) return [];
        $kbxToken = new KbxToken();
        //从订单系统获取订单信息
        $url = $kbxToken->bSellerBackendUrl.'/expedia/getERegionByEId?eId='.$eId;
        $token = 'Bearer ' . $kbxToken->kbxToken();
        $res = $kbxToken->get_data($url,$token);
        //记录日志
        trace('获取订单系统缓存的expedia的城市详情');
        trace('请求地址：'.$url);
        return $res;
    }
}